import Taro from "@tarojs/taro";
import { View, Text, Image } from "@tarojs/components";
import React, { useState } from "react";
import { addLiked, cancelLiked } from "./api";
import def from "../../assets/default.jpg";
import like from "../../assets/card/like.svg";
import dislike from "../../assets/card/dislike.svg";
import css from "./index.module.less";

export default function Index(props) {
  const article = props.article;
  const images = props.images;
  const [isLiked, setIsLiked] = useState(props.liked);
  const [likes, setLikes] = useState(article.likes);

  const [isLoad, setIsLoad] = useState(false);

  const likeOrDislike = (event, article) => {
    event.stopPropagation();
    Taro.getStorage({
      key: "userInfo",
      success: function (res) {
        const result = res.data;
        const userId = result.uuid;
        console.log(article);
        const data = {
          articleId: article.uuid,
          userId: userId,
          likes: likes,
        };
        if (isLiked) {
          cancelLiked(data).then((result) => {
            setIsLiked(!isLiked);
            setLikes(likes - 1);
            if (result.code === 200) {
              console.log(result.data);
              console.log("ok");
            } else {
              setLikes(likes - 1);
              console.log(result.msg);
            }
          });
        } else {
          addLiked(data).then((result) => {
            setIsLiked(!isLiked);
            setLikes(likes + 1);
            if (result.code === 200) {
              console.log(result.data);
              console.log("ok");
            } else {
              setLikes(likes - 1);
              console.log(result.msg);
            }
          });
        }
        // getArticle(data.uuid, 1, 10);
        // console.log(res.data)
      },
      fail: function (err) {
        // getArticle(null, 1, 10);
      },
    });
    // const userId = "adcb27a2-d837-49f6-9e4d-75898f538a8f";
  };
  const onLoad = () => {
    setIsLoad(true);
  };
  const onError = () => {
    setIsLoad(false);
  };
  return (
    <View className={css.content}>

      <Image className={css.image} src={isLoad? images[0].url : def} onLoad={onLoad} onError={onError} />
      <View className={css.title} style>
        {article.title}
      </View>
      <View className={css.bottom}>
        <View className={css.author}>{article.author}</View>
        <View
          className={css.author}
          onClick={(event) => likeOrDislike(event, article)}
        >
          <Image src={isLiked ? like : dislike} defaultSource={dislike}  />
          <Text>{likes}</Text>
        </View>
      </View>
    </View>
  );
}
